package tchk.xyz.lingyuntutorminiprogram.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import tchk.xyz.lingyuntutorminiprogram.dto.RoleDTO;
import tchk.xyz.lingyuntutorminiprogram.entity.SysPermission;
import tchk.xyz.lingyuntutorminiprogram.entity.SysRole;
import tchk.xyz.lingyuntutorminiprogram.service.ISysPermissionService;
import tchk.xyz.lingyuntutorminiprogram.service.ISysRoleService;
import tchk.xyz.lingyuntutorminiprogram.utils.Result;

import java.util.List;

@RestController
@RequestMapping("/api/admin/role")
@PreAuthorize("hasAuthority('admin:role:manage')")
public class RoleController {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPermissionService permissionService;

    @GetMapping("/list")
    public Result<Page<SysRole>> getRoleList(@RequestParam(defaultValue = "1") long current,
                                             @RequestParam(defaultValue = "10") long size) {
        Page<SysRole> page = new Page<>(current, size);
        return Result.success(roleService.page(page));
    }

    @GetMapping("/{id}")
    public Result<RoleDTO> getRoleDetail(@PathVariable Long id) {
        return Result.success(roleService.getRoleWithPermissions(id));
    }

    @PostMapping
    public Result<Void> addRole(@RequestBody RoleDTO roleDTO) {
        roleService.saveRoleWithPermissions(roleDTO);
        return Result.success();
    }

    @PutMapping
    public Result<Void> updateRole(@RequestBody RoleDTO roleDTO) {
        roleService.updateRoleWithPermissions(roleDTO);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteRole(@PathVariable Long id) {
        // TODO: 删除前检查角色是否已被用户关联
        roleService.removeById(id);
        // 也需要删除关联表中的数据
        // sysRolePermissionService.remove(new LambdaQueryWrapper<SysRolePermission>().eq(SysRolePermission::getRoleId, id));
        return Result.success();
    }

    /**
     * 获取所有权限列表（用于前端分配权限的穿梭框）
     */
    @GetMapping("/permissions")
    public Result<List<SysPermission>> getAllPermissions() {
        return Result.success(permissionService.list());
    }
}